<!DOCTYPE html>
<html lang="zh">
<head>
  <title>Centrifugo 实时通信演示</title>
  <!--    <script src="https://unpkg.com/centrifuge@5.4.0/dist/centrifuge.js"></script>-->
  <script src="./centrifuge@5.4.0/dist/centrifuge.js"></script>
  <style>
      body {
          font-family: Arial, sans-serif;
          margin: 20px;
      }

      .container {
          max-width: 800px;
          margin: 0 auto;
      }

      .btn {
          padding: 10px 15px;
          margin: 5px;
          border: none;
          border-radius: 4px;
          cursor: pointer;
      }

      .input {
          padding: 10px 15px;
          margin: 5px;
          border-radius: 4px;
      }

      .connect {
          background: #4CAF50;
          color: white;
      }

      .subscribe {
          background: #2196F3;
          color: white;
      }

      .publish {
          background: #FF9800;
          color: white;
      }

      .demo {
          background: #9C27B0;
          color: white;
      }

      #messages {
          border: 1px solid #ddd;
          padding: 15px;
          height: 300px;
          overflow-y: auto;
          margin: 10px 0;
      }

      .message {
          margin: 5px 0;
          padding: 8px;
          border-left: 4px solid #4CAF50;
          background: #f9f9f9;
      }

      .error {
          border-left-color: #f44336;
          background: #ffebee;
      }
  </style>
</head>
<body>
<div class="container">
  <h1>🔗 Centrifugo 实时通信演示</h1>

  <div>
    <button class="btn connect" onclick="connect()">连接Centrifugo</button>
    <button class="btn subscribe" onclick="subscribe('news')">订阅新闻频道</button>
    <button class="btn subscribe" onclick="subscribe('updates')">订阅更新频道</button>
    <button class="btn subscribe" onclick="subscribe('notifications')">订阅通知频道</button>
    <button class="btn demo" onclick="sendDemoMessages()">发送演示消息</button>
  </div>

  <div id="status">状态: 未连接</div>

  <h3>收到的消息:</h3>
  <div id="messages"></div>

  <div>
    <h3>发送自定义消息:</h3>
    <input class="input" type="text" id="channelInput" placeholder="频道名称" value="news">
    <input class="input" type="text" id="messageInput" placeholder="消息内容" value="Hello World!">
    <button class="btn publish" onclick="sendCustomMessage()">发送消息</button>
  </div>
</div>

<script>
  var tokenKey = 'token'
  var userKey = 'userInfo'

  function setToken(token) {
    localStorage.setItem(tokenKey, token)
  }

  function getToken() {
    return localStorage.getItem(tokenKey) || null;
  }

  function setUserInfo(data) {
    localStorage.setItem(userKey, data)
  }

  function getUserInfo() {
    return localStorage.getItem(userKey) || null;
  }

  function getUserId() {
    data = getUserInfo();
    if (data) {
      return data.id;
    }
    userData = {};
    currentUserId = 'user-' + Math.random().toString(36).substr(2, 5);
    userData.id = currentUserId;
    userData.name = currentUserId
    setUserInfo(JSON.stringify(userData))
    return currentUserId
  }

  let centrifuge = null;
  let currentUserId = '';
  const subscriptions = {};

  // 1. 从Go服务器获取Token
  async function fetchToken(userId) {
    try {
      token = getToken();
      if (token) {
        return token;
      }
      addMessage('🔄 正在获取Token...', 'info');
      const response = await fetch(`http://localhost:8080/token?user=${userId}`);
      const data = await response.json();
      addMessage('✅ Token获取成功', 'success');
      setToken(data.token)
      return data.token;
    } catch (error) {
      addMessage('❌ 获取Token失败: ' + error, 'error');
      throw error;
    }
  }

  // 2. 连接到Centrifugo
  async function connect() {
    try {
      currentUserId = getUserId()
      const token = await fetchToken(currentUserId);

      centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket', {
        token: token // 只使用 token，去掉 headers
      });

      centrifuge.on('connected', function (ctx) {
        updateStatus('✅ 已连接', 'connected');
        addMessage('🎉 成功连接到Centrifugo服务器', 'success');
      });

      centrifuge.on('disconnected', function (ctx) {
        updateStatus('❌ 连接断开', 'disconnected');
        addMessage('连接已断开', 'error');
      });

      centrifuge.on('error', function (ctx) {
        addMessage('错误: ' + ctx.error.message, 'error');
      });

      centrifuge.connect();

    } catch (error) {
      addMessage('连接失败: ' + error, 'error');
    }
  }

  // 3. 订阅频道
  async function subscribe(channel) {
    if (!centrifuge) {
      addMessage('请先点击"连接"按钮', 'error');
      return;
    }

    if (subscriptions[channel]) {
      addMessage(`已经订阅了频道: ${channel}`, 'info');
      return;
    }

    try {
      const sub = centrifuge.newSubscription(channel);

      sub.on('publication', function (ctx) {
        addMessage(`📨 [${channel}] ${JSON.stringify(ctx.data)}`, 'message');
      });

      sub.on('subscribed', function (ctx) {
        addMessage(`📡 已订阅频道: ${channel}`, 'success');
      });

      sub.on('error', function (ctx) {
        addMessage(`订阅错误 [${channel}]: ${ctx.error.message}`, 'error');
      });

      sub.subscribe();
      subscriptions[channel] = sub;

    } catch (error) {
      addMessage(`订阅频道 ${channel} 失败: ${error}`, 'error');
    }
  }

  // 4. 发送演示消息（通过Go服务器）
  async function sendDemoMessages() {
    try {
      addMessage('🔄 发送演示消息...', 'info');
      const response = await fetch('http://localhost:8080/demo');
      const result = await response.json();
      addMessage('✅ ' + result.status, 'success');
    } catch (error) {
      addMessage('❌ 发送演示消息失败: ' + error, 'error');
    }
  }

  // 5. 发送自定义消息
  async function sendCustomMessage() {
    const channel = document.getElementById('channelInput').value;
    const messageText = document.getElementById('messageInput').value;

    if (!channel || !messageText) {
      addMessage('请填写频道和消息内容', 'error');
      return;
    }

    try {
      const message = {
        text: messageText,
        time: new Date().toLocaleTimeString(),
        from: currentUserId
      };

      const response = await fetch('http://localhost:8080/publish', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          channel: channel,
          message: message
        })
      });

      const result = await response.json();
      if (response.ok) {
        addMessage(`✅ 消息已发送到频道 [${channel}]`, 'success');
      } else {
        addMessage('❌ 发送失败: ' + result.message, 'error');
      }
    } catch (error) {
      addMessage('❌ 发送消息失败: ' + error, 'error');
    }
  }

  // 工具函数
  function addMessage(text, type = 'info') {
    const messagesDiv = document.getElementById('messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = `[${new Date().toLocaleTimeString()}] ${text}`;
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  }

  function updateStatus(text, status) {
    const statusDiv = document.getElementById('status');
    statusDiv.textContent = `状态: ${text}`;
    statusDiv.className = status;
  }

  connect()
</script>
</body>
</html>